//
//  DynamicViewController.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/10/27.
//

#import "DynamicViewController.h"
#import "SearchView.h"
#import "ShopModel.h"
#import "DynamicTableView.h"
#import "DynamicTableViewCell.h"
#import <GKPhotoBrowser/GKPhotoBrowser.h>
#import "ShopInfoViewController.h"
#import "NoticeView.h"
#import "PublishShopViewController.h"
#import "ShopViewController.h"
#import "ScanCodeViewController.h"

@interface DynamicViewController ()<GKPhotoBrowserDelegate>

@property (nonatomic, assign) NSInteger lastIndex;
@property (nonatomic, strong) SearchView *searchV;
@property (nonatomic, copy) NSString *searchStr;
@property (nonatomic, strong) NSMutableArray *modelArr;
@property (nonatomic, strong) DynamicTableView *tableview;
@property (nonatomic, weak) GKPhotoBrowser *browser;
@property (nonatomic, strong) NoticeView *noticeV;

@end

@implementation DynamicViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.lastIndex = 0;
    [self requestData];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self.modelArr enumerateObjectsUsingBlock:^(ShopModelFrame *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.width = kWidthForScreen;
        [obj updateFrameWithWidth:obj.width];
    }];
    [self.tableview.visibleCells enumerateObjectsUsingBlock:^(__kindof DynamicTableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj updateFrame];
    }];
}

- (void)initDidLoad {
    self.hbd_barHidden = YES;
    self.lastIndex = 0;
}

- (void)initViews {
    [self.view addSubview:self.searchV];
    [self.view addSubview:self.tableview];
    
    [self.searchV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(0);
        make.top.mas_equalTo(kHeightForStatusBar);
        make.height.mas_equalTo(56);
    }];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.searchV.mas_bottom);
    }];
}

- (void)reloadViews:(NSArray *)arr {
    [self.view addSubview:self.noticeV];
    [self.noticeV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.width.mas_equalTo(kWidthForScreen);
        make.height.mas_equalTo(28);
        make.top.mas_equalTo(self.searchV.mas_bottom).offset(5);
    }];
    [self.tableview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.noticeV.mas_bottom).offset(5);
        make.leading.trailing.bottom.mas_equalTo(0);
    }];
}

#pragma mark - request
- (void)initRequestData {
    [NET getNoticeDataSuccess:^(id  _Nonnull responseObject) {
        NSArray *arr = responseObject[@"content"];
        if (arr.count > 0) {
            [self reloadViews:arr];
            self.noticeV.titleArr = arr;
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestData {
    [NET getDynamicGoodsList:@(self.lastIndex) pageSize:@(self.pageSize) searchStr:self.searchStr success:^(id  _Nonnull responseObject) {
        NSArray *arr = [ShopModel mj_objectArrayWithKeyValuesArray:responseObject[@"content"]];
        if (self.lastIndex == 0) {
            [self.modelArr removeAllObjects];
        }
        [self.modelArr addObjectsFromArray:[self dataPraseWithModel:arr]];
        self.tableview.modelArr = self.modelArr;
        [self.tableview reloadData];
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        self.lastIndex = [responseObject[@"lastIndex"] integerValue];
    } failure:^(NSError * _Nonnull error) {
        kShowText(error.userInfo[kHttpErrorReason]);
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
    }];
}

- (NSArray *)dataPraseWithModel:(NSArray *)models {
    NSMutableArray *arr = [NSMutableArray array];
    for (ShopModel *model in models) {
        ShopModelFrame *f = [[ShopModelFrame alloc] init];
        NSMutableArray *imageModelArr = [NSMutableArray array];
        NSMutableArray *thumArr = [NSMutableArray array];
        NSMutableArray *imageUrlArr = [NSMutableArray array];
        if (model.video.length > 0) {
            [thumArr addObject:model.videoPicUrl];
            [imageUrlArr addObject:model.videoPicUrl];
        }
        [thumArr addObjectsFromArray:model.imgThumbnailUrl];
        [imageUrlArr addObjectsFromArray:model.imgUrl];
        
        for (int i = 0; i < (thumArr.count >= imageUrlArr.count ? thumArr.count : imageUrlArr.count); i++) {
            ShopModelImageModel *imgModel = [[ShopModelImageModel alloc] init];
            NSString *thumUrl = thumArr[i];
            NSString *imaurl = imageUrlArr[i];
            imgModel.imgThumbnailUrl = thumUrl;
            imgModel.imgUrl = imaurl;
            if (model.video.length >0 && i == 0) {
                imgModel.video = model.video;
            }
            [imageModelArr addObject:imgModel];
        }
        f.width = kWidthForScreen;
        model.imageModels = imageModelArr;
        f.model = model;
        
        [arr addObject:f];
    }
    return arr;
}

/// 一键转发商品
- (void)forwardGoods:(ShopModel *)model {
    [YPProgressHud showHudInview:self.view];
    [NET forwardGoodsWithGoodsId:model.goodsId success:^(id  _Nonnull responseObject) {
        kShowText(@"转发成功");
        self.lastIndex = 0;
        [self requestData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

/// 同步更新
- (void)updateGoods:(ShopModel *)model {
    [YPProgressHud showHudInview:self.view];
    [NET updateGoodsWithGoodsId:model.goodsId success:^(id  _Nonnull responseObject) {
        kShowText(@"同步完成");
        self.lastIndex = 0;
        [self requestData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
    }];
}


#pragma mark - 懒加载
- (SearchView *)searchV {
    if (!_searchV) {
        _searchV = [[SearchView alloc] init];
        @weakify(self)
        _searchV.searchBlock = ^(NSString * _Nonnull searchStr) {
         @strongify(self)
            self.searchStr = searchStr;
            self.lastIndex = 0;
            [self requestData];
        };
        _searchV.qrBlock = ^{
          @strongify(self)
            ScanCodeViewController *vc = [[ScanCodeViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        _searchV.clearBlcok = ^{
          @strongify(self)
            self.searchStr = nil;
            self.lastIndex = 0;
            [self requestData];
        };
    }
    return _searchV;
}

- (NSMutableArray *)modelArr {
    if (!_modelArr) {
        _modelArr = [NSMutableArray array];
    }
    return _modelArr;
}

- (DynamicTableView *)tableview {
    if (!_tableview) {
        _tableview = [[DynamicTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        @weakify(self)
        _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
         @strongify(self)
            self.lastIndex = 0;
            [self requestData];
        }];
        _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self requestData];
        }];
        [_tableview setPhotosViewClick:^(DynamicTableViewCell * _Nonnull cell, NSInteger index) {
            @strongify(self)
            [self showPhotoWithCell:cell index:index];
        }];
        [_tableview.subject subscribeNext:^(NSIndexPath *x) {
           @strongify(self)
            ShopModelFrame *f = self.modelArr[x.row];
            ShopInfoViewController *vc = [[ShopInfoViewController alloc] init];
            vc.goodsId = f.model.goodsId;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        [_tableview setUpdateGoodsBlock:^(ShopModel * _Nonnull model) {
           @strongify(self)
            [self updateGoods:model];
        }];
        [_tableview setTransBlock:^(ShopModel * _Nonnull model) {
           @strongify(self)
            [self forwardGoods:model];
        }];
        [_tableview setEditTransBlock:^(ShopModel * _Nonnull model) {
           @strongify(self)
            PublishShopViewController *vc = [[PublishShopViewController alloc] init];
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        [_tableview setGoShopBlock:^(ShopModel * _Nonnull model) {
            @strongify(self)
            ShopViewController *vc = [[ShopViewController alloc] init];
            vc.isPush = YES;
            vc.userId = model.userId;
            [self.navigationController pushViewController:vc animated:YES];
        }];
    }
    return _tableview;
}

- (NoticeView *)noticeV {
    if (!_noticeV) {
        _noticeV = [[NoticeView alloc] init];
        _noticeV.backgroundColor = kRGB(0xFEF9E0);
    }
    return _noticeV;
}


- (void)showPhotoWithCell:(DynamicTableViewCell *)cell index:(NSInteger)index {
    NSMutableArray *photoArr = [NSMutableArray array];
    [cell.frameModel.model.imageModels enumerateObjectsUsingBlock:^(ShopModelImageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GKPhoto *photo = [[GKPhoto alloc] init];
        photo.url = [NSURL URLWithString:obj.imgUrl];
        photo.sourceImageView = cell.photosView.subviews[idx];
        if (obj.isVideo) {
            photo.videoUrl = [NSURL URLWithString:obj.video];
        }
        [photoArr addObject:photo];
    }];
    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photoArr currentIndex:index];
    browser.showStyle = GKPhotoBrowserShowStyleZoom;
    browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
    browser.loadStyle = GKPhotoBrowserLoadStyleIndeterminateMask;
    browser.maxZoomScale = 20.0f;
    browser.doubleZoomScale = 2.0f;
    browser.isAdaptiveSafeArea = YES;
    browser.hidesCountLabel = YES;
    browser.hidesSavedBtn = YES;
    browser.isFullWidthForLandScape = NO;
    browser.isSingleTapDisabled = YES;
    browser.showPlayImage = NO;
    browser.isVideoReplay = YES;
    browser.videoPlayImage = [UIImage imageNamed:@"shopinfo_play"];
    browser.delegate = self;
    [browser showFromVC:self];
    self.browser = browser;
}

- (void)photoBrowser:(GKPhotoBrowser *)browser singleTapWithIndex:(NSInteger)index {
    [browser dismiss];
}

@end
